<template>
  <div>
   <el-header style="display: flex; align-items: center; justify-content: flex-start; padding-left: 5px; margin-top:5px; margin-bottom:5px">
    <i class="el-icon-location-information" style="font-size:20px; margin-right:5px">
    当前位置：设备信息管理
    </i>
  </el-header>

    <div class="search" style="display: flex; align-items: center; justify-content: space-between; padding-left: 5px;">
       <div style="display: flex; align-items: center;">
        <el-select v-model="selectedColumn" placeholder="选择搜索列" style="margin-right: 10px; width: 150px;">
          <el-option label="设备名称" value="field1"></el-option>
          <el-option label="设备型号" value="field2"></el-option>
          <el-option label="所在产线" value="field3"></el-option>
          <el-option label="责任人" value="field4"></el-option>
          <el-option label="设备规格" value="field5"></el-option>
          <el-option label="设备厂商" value="field6"></el-option>
          <el-option label="所属站位" value="field7"></el-option>
          <el-option label="设备编号" value="field8"></el-option>
          <el-option label="设备运行状态" value="field9"></el-option>
          <el-option label="异常持续时间" value="field10"></el-option>
          <el-option label="异常描述" value="field11"></el-option>
        </el-select>

        <input type="text" v-model="searchKeyword" placeholder="输入关键词搜索" style="margin-right: 10px; width: 200px;">
        <button @click="search">
          <i class="el-icon-search"></i>
        </button>
       </div>
       <div style="display: flex; align-items: center;">
        <button @click="fetchData" style="margin-left: 50px;">加载数据库内容</button>
        <button @click="exportToExcel" style="margin-left: 50px;">导出为Excel</button>
       </div>
      </div>
    <div class="table-container">
    <table class="custom-table">
      <thead>
        <tr>
          <th>序号</th>
          <th>设备名称</th>
          <th>设备型号</th>
          <th>所在产线</th>
          <th>责任人</th>
          <th>设备规格</th>
          <th>设备厂商</th>
          <th>所属站位</th>
          <th>设备编号</th>
          <th>设备运行状态</th>
          <th>异常持续时间</th>
          <th>异常描述</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in currentData" :key="item.field1">
          <td>{{ index+1+(currentPage-1)*itemsPerPage }}</td>
          <td>{{ item.field1 }}</td>
          <td>{{ item.field2 }}</td>
          <td>{{ item.field3 }}</td>
          <td>{{ item.field4 }}</td>
          <td>{{ item.field5 }}</td>
          <td>{{ item.field6 }}</td>
          <td>{{ item.field7 }}</td>
          <td>{{ item.field8 }}</td>
          <td>{{ item.field9 }}</td>
          <td>{{ item.field10 }}</td>
          <td>{{ item.field11 }}</td>
        </tr>
      </tbody>
    </table>
    </div>

<div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="userItemsPerPage"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.length">
      </el-pagination>
    </div>




</div>
</template>

<script>
import axios from 'axios';
import * as XLSX from 'xlsx';
//在进入这个页面前调用fetch函数，加载数据库数据
export default {
      // 在你的组件中定义路由钩子函数

  // 在组件内部定义 beforeRouteEnter 导航守卫
  beforeRouteEnter(to, from, next) {
    // 在进入路由之前执行初始化函数
    // 由于在这里无法访问组件实例 this，你需要通过 next() 回调函数访问组件实例
    next(vm => {
      // 调用组件实例的初始化函数
      vm.fetchData(); // 假设你的初始化函数叫做 initialize()
    });
  },
  //返回一个对象，包含各种数据
  data() {
    return {
      currentPage: 1, // 当前页码
      userItemsPerPage: 10, // 每页显示条数
      items:[],//从数据库中获得的数据
      currentData:[/*当前页面的数据*/],
      data: [/* 初始数据 */],
      currentPage: 1,
      itemsPerPage: 3,//每页显示的数量
      searchKeyword: '',//搜索关键字
      selectedColumn: 'field1',
    };
  },

computed: {
       displayedData() {
      const startIndex = (this.currentPage - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      return this.currentData.slice(startIndex, endIndex);
    },
filteredData() {
  if (!this.searchKeyword) {
    return this.data;
  }

  return this.data.filter(item => {
    for (let i = 1; i <= 11; i++) {
      const field = item[`field${i}`];
      if (typeof field === 'string' && field.includes(this.searchKeyword)) {
        return true;
      } else if (typeof field === 'number' && field.toString().includes(this.searchKeyword)) {
        return true;
      }
    }
    return false;
  });
},

    totalPages() {
      return Math.ceil(this.filteredData.length / this.itemsPerPage);
    }
  },

  methods: {
    handleSizeChange(val) {
      this.userItemsPerPage = val; // 更新每页显示条数
      this.updateCurrentData(); // 调用方法更新当前数据
    },
    handleCurrentChange(val) {
      this.currentPage = val; // 更新当前页码
      this.updateCurrentData(); // 调用方法更新当前数据
    },
    showplan(index){
      alert(index+'还没做好')
    },
    exportToExcel() {
      const data = this.data;
      const adjustedData = data.map(obj => Object.values(obj));
      const worksheet = XLSX.utils.aoa_to_sheet(adjustedData);
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const url = URL.createObjectURL(blob);

      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', 'exported_data.xlsx');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },


     async fetchData() {
      try {
       this.data = []
        // 发送请求获取数据
        const response = await axios.get('http://localhost:8000/api/equipment/query');
                   // 判断是否成功获取了数据
    if (response) {
      // 将获取的数据存储在组件中
      this.items = response.data;
      console.log('Data fetched successfully:', this.items);
       // 遍历 items 中的每个对象，将数据更新到 data 中
       
      this.items.forEach(item => {
        const newDataObject = {};
        newDataObject['field1'] = item.name;//设备名称
        newDataObject['field2'] = item.model;//设备型号
        newDataObject['field3'] = item.line;//所在产线
        newDataObject['field4'] = item.responsible_person;//责任人
        newDataObject['field5'] = item.type;//设备规格
        newDataObject['field6'] = item.manufacturer;//设备厂商
        newDataObject['field7'] = item.position_zw;//所属站位
        newDataObject['field8'] = item.serial_number;//设备编号
        newDataObject['field9'] = item.operating_state;//设备运行状态
        newDataObject['field10'] = item.exception_duration;//异常持续时间
        newDataObject['field11'] = item.description;//异常描述

        this.data.push(newDataObject);
        this.currentData = this.getCurrentPageData(this.data, this.currentPage, this.itemsPerPage)
        });
        }
         else {
      console.error('Failed to fetch data.');
      alert('Failed to fetch data.');
    }
         
    
 
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    },

    firstPage() {
      this.currentPage = 1;
      this.currentData = this.getCurrentPageData(this.data, this.currentPage, this.itemsPerPage);
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      this.currentData = this.getCurrentPageData(this.data, this.currentPage, this.itemsPerPage);
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
      this.currentData = this.getCurrentPageData(this.data, this.currentPage, this.itemsPerPage);
      }
    },
    lastPage() {
      this.currentPage = this.totalPages;
    this.currentData = this.getCurrentPageData(this.data, this.currentPage, this.itemsPerPage);
    },
    search() {
      if (!this.selectedColumn || !this.searchKeyword) {
        this.currentData = this.getCurrentPageData(this.data, this.currentPage, this.itemsPerPage);
        return;
      }

      this.currentData = this.data.filter(item => {
        const field = item[this.selectedColumn];
        if (typeof field === 'string' && field.includes(this.searchKeyword)) {
          return true;
        } else if (typeof field === 'number' && field.toString().includes(this.searchKeyword)) {
          return true;
        }
        return false;
      });

      this.currentData = this.getCurrentPageData(this.currentData, this.currentPage, this.itemsPerPage);
    },
//从数据库信息中提取当前页面应该有的信息，其他函数调用，赋值给currentData
  getCurrentPageData(data, currentPage, itemsPerPage) {
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    return data.slice(startIndex, endIndex);
},

  }
};
</script>

<style>
.table-container {
  text-align: center;
  margin: auto;
}

.custom-table {
  border-collapse: collapse;
  width: 80%;
  margin-bottom: 20px;
}

.custom-table th,
.custom-table td {
  border: 1px solid black;
  padding: 8px;
}

.pagination {
  margin-top: 20px;
}

.pagination button {
  margin-right: 5px;
}
</style>
